<template>
<el-container>
<!--       aside -->
<!--      100vh为整个窗口高度-->
<el-aside style="width:200px; min-height: 1000px;background-color: #15293b">
  <div style="height: 60px; color: aliceblue; display: flex; align-items: center;justify-content: center" >
    <img :src="require('@/assets/library.jpg')" style="height: 80%;">
  </div>
  <!--        侧边导航栏-->

  <el-menu style="border: none" :default-active="$route.path" router... background-color="#15293b" text-color="rgba(255,255,255,0.65)" active-text-color="#FFF" @select="handleSelect">

    <el-menu-item index="/login">
      <template slot="title">
        <i class="el-icon-right"></i>
        <span>登录界面</span>
      </template>
    </el-menu-item>
    <el-menu-item index="/home">
      <template slot="title">
        <i class="el-icon-s-marketing"></i>
        <span>系统首页</span>
      </template>
    </el-menu-item>
    <el-menu-item index="/about">
      <template slot="title">
        <i class="el-icon-user"></i>
        <span>用户管理</span>
      </template>
    </el-menu-item>
    <el-menu-item index="/product">
      <template slot="title">
        <i class="el-icon-collection"></i>
        <span>书籍管理</span>
      </template>
    </el-menu-item>
    <el-submenu>
      <template slot="title">
        <i class="el-icon-loading"></i>
        <span></span>
      </template>
    </el-submenu>
  </el-menu>
</el-aside>


<el-container>
  <!-- header -->
  <el-header style="display: flex; align-items: center; justify-content: space-between; height: 60px; background-color: #2c3e50; color: white;">
    <div style="text-align: center; width: 100%;">图书管理系统</div>
    <el-tooltip class="item" effect="dark" content="新消息" placement="top" style="margin-right: 40px">
      <el-badge  class="item">
        <el-button @click="notice()" size="mini" type="primary" icon="el-icon-message-solid" circle></el-button>
      </el-badge>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="个人中心" placement="top" style="margin-right: 20px">
      <el-badge  class="item">
        <el-button @click="personCenter()" size="mini" type="primary" icon="el-icon-user-solid" circle></el-button>
      </el-badge>
    </el-tooltip>
  </el-header>

  <!-- main -->
  <el-main>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" >
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="用户名" prefix-icon="el-icon-search"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="onSubmit()">查询</el-button>
      </el-form-item>
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="update()">刷新</el-button>
      </el-form-item>
<!--      <el-button type="success" round style="margin-left: 60px" @click="createBook">新增用户</el-button>-->
    </el-form>

    <el-dialog title="用户信息" :visible.sync="dialogFormVisible2">
      <el-form label-width="100px" size="small">
        <!--                  编辑对话框-->
        <el-form-item label="bookname" >
          <el-input v-model="createData.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="author" >
          <el-input v-model="createData.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="category" >
          <el-input v-model="createData.category" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" >
          <el-input v-model="createData.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="余量" >
          <el-input v-model="createData.surplus" autocomplete="off"></el-input>
        </el-form-item>
        <!--                  编辑对话框-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="uploadBook()">确 定</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" border>
      <el-table-column prop="userid" label="ID" width="250" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="250" align="center">
      </el-table-column>
      <el-table-column prop="category" label="类型" width="250" align="center">
      </el-table-column>
      <el-table-column label="是否管理员" width="250" align="center">
        <template slot-scope="scope">
          {{ scope.row.is_admin ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column  label="书籍数目" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.books_num === 0 ? '无书籍' : scope.row.books_num }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="updateUser(scope.row.userid)" style="margin-right: 15px;">编辑</el-button>
          <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
            <el-form label-width="100px" size="small">
              <!--                  编辑对话框-->
              <el-form-item label="username" >
                <el-input v-model="updateData.username" autocomplete="off"  disabled></el-input>
              </el-form-item>
              <el-form-item label="newusername" >
                <el-input v-model="updateData.new_username" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="密码" >
                <el-input v-model="updateData.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="类型">
                <el-radio-group v-model="updateData.category">
                  <el-radio label="student">学生</el-radio>
                  <el-radio label="teacher">教师</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否管理员">
                <el-switch
                    v-model="updateData.is_admin"
                    active-value=1
                    inactive-value=0>
                </el-switch>
              </el-form-item>
              <!--                  编辑对话框-->
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateComfirm()">确 定</el-button>
            </div>
          </el-dialog>

          <el-button @click="deleteUser(scope.row.userid)" size="mini" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 20px"
                   background
                   layout=" prev, pager, next, total"  @current-change="handleCurrentChange"
                   :total="fullData.length" :current-page="currentPage" :page-size="pageSize">
    </el-pagination>

  </el-main>
</el-container>
</el-container>
</template>
<script>
import axios from 'axios';
import Cookies from "js-cookie";
export default {
  data() {
    return {
      is_admin:false,
      username:'',
      password:'',
      fullData: [], // 存储从服务器获取的所有数据
      tableData: [],
      updateData: [],
      categorys: [],
      createData:[],
      dialogFormVisible:false,
      dialogFormVisible2:false,
      currentPage: 1,
      pageSize: 10,
      searchForm: {
        username: ''
      }
    }
  },
  methods:{
    notice(){
      if(!this.is_admin){
        this.$router.push({ name: 'notice'});
      }
      else {
        this.$router.push({ name: 'adminnotice'});
      }
    },
    personCenter(){
      const message = "this is admin";
      this.$router.push({ name: 'person', params: { message }});
    },
    handleSelect(index) {
      const routeData = {
        path: index,
        query: {
          username: this.username,
          password: this.password,
        }
      };

      this.$router.push(routeData).catch(err => {
        // 如果路由跳转发生错误，你可以在这里处理
        console.error('Route navigation failed:', err);
      });
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getFull();
    },
    getFull() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.fullData.slice(start, end);
    },
    updateComfirm() {
      // 检查用户名和密码是否为空
      if (this.updateData.new_username == '' || this.updateData.password == '') {
        // 使用Element UI的MessageBox或者Notification组件来给用户提示消息
        this.$message({
          message: '用户名和密码不能为空',
          type: 'warning'
        });
        return; // 阻止函数进一步执行
      }

      // 如果用户名和密码都不为空，则执行下面的代码
      this.dialogFormVisible = false;

      axios.put('http://127.0.0.1:5000/v1/admin/editUserInfo',
          {
            userid: this.updateData.userid,
            username: this.updateData.username,
            new_username: this.updateData.new_username,
            new_password: this.updateData.password,
            new_category: this.updateData.category,
            new_is_admin: this.updateData.is_admin === '1' ? true : false,
          },
          { headers: { 'Content-Type': 'application/json', 'token': Cookies.get('token')} }
      )
          .then(() => {
            this.$message.success('更新成功')
            this.update(); // 这里假设update是你用来刷新数据的方法
          })
          .catch(error => {
            console.error('Error:', error);
            let message = '更新失败，请稍后再试';
            if (error.response && error.response.data && error.response.data.message) {
              message = error.response.data.message; // 假设后端返回的错误信息格式为 { message: "错误信息" }
            }
            this.$message({
              message: message,
              type: 'error'
            });
          });
    },
    updateUser(userid){
      this.dialogFormVisible = true;
      axios.get(`http://127.0.0.1:5000/v1/admin/getUserByID/${userid}`, {
        headers: {
          'token': Cookies.get('token') // 获取 token 并添加到请求头中
        }
      })
          .then(response => {
            this.updateData = response.data.data;
          })
          .catch(error => {
            this.$message({
              type: 'error',
              message: '更新失败'
            });
            console.error("Error deleting user:", error.response);
          })
          .finally(() => {
            this.update();
          });
    },
    onSubmit(){
      axios.get(`http://127.0.0.1:5000/v1/admin/getUserByName/${this.searchForm.username}`, {
        headers: {
          token: Cookies.get('token')
        }
      })
          .then(response => {
            this.currentPage = 1;
            this.fullData = response.data.data;
            console.log(this.fullData)
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.tableData = this.fullData.slice(start, end);
          })
          .catch((error) => {
            console.error('请求失败:', error);
          });
    },
    update() {
      // 发送异步请求获取数据
      axios.get('http://127.0.0.1:5000/v1/admin/getAllusers', {
        headers: {
          token: Cookies.get('token')
        }
      })
          .then(response => {
            this.searchForm.username = '';
            this.currentPage = 1;
            this.fullData = response.data.data;
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.tableData = this.fullData.slice(start, end);
            this.itemNumber = this.fullData.length;
          })
          .catch(() => {
            // 处理错误
          });
    },
    deleteUser(userid) {
      axios.delete(`http://127.0.0.1:5000/v1/admin/deleteUser/${userid}`, {
        headers: {
          'token': Cookies.get('token') // 获取 token 并添加到请求头中
        }
      })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            // 执行删除后的分页操作以及表的更新可以放在这里或者在 finally 中
          })
          .catch(error => {
            this.$message({
              type: 'error',
              message: '删除失败'
            });
            console.error("Error deleting user:", error.response);
          })
          .finally(() => {
            this.update(); // 确保无论成功还是失败，都会调用 update 方法
          });
    }
  },
  mounted() {
    //   发送异步请求获取数据
    axios.get('http://127.0.0.1:5000/v1/admin/getAllusers', {
      headers: {
        token: Cookies.get('token')
      }
    })
        .then(response => {
          this.fullData = response.data.data;
          const start = (this.currentPage - 1) * this.pageSize;
          const end = start + this.pageSize;
          this.tableData = this.fullData.slice(start, end);
          this.itemNumber = this.fullData.length;
        })
        .catch(() => {
          // 处理错误
        });
    this.username = Cookies.get('username');
    this.password = Cookies.get('password');
    this.is_admin = Cookies.get('is_admin');
  }
}
</script>